package com.awspaas.user.apps.cpq.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.commons.database.RowMap;
import com.actionsoft.bpms.commons.mvc.view.ResponseObject;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class CPQ_GetInstallationFeeAllModuleNumberWeb {

	public String getInstallationFeeAllModuleNumber(UserContext userContext, String bindId, String cs, String datas) {
		// 将数组转换为列表
		 JSONArray list=JSONObject.parseArray(cs);		
		JSONArray mList=JSONObject.parseArray(datas);	
		// 获取模块所需参数信息
		Map<String, String> pMap = new HashMap<String, String>();
		Map<String, String> nameMap = new HashMap<String, String>();
		Map<String, String> noMap = new HashMap<>();
		for (int i = 0; i < list.size(); i++) {
			JSONObject json = (JSONObject) list.get(i);
			String bh = (String) json.get("PARMENTIER_NO");
			String value = (String) json.get("PARMENTIER_VALUE");
			String name = (String) json.get("PARMENTIER_NAME");
			String dw = (String) json.get("DW");
			pMap.put(bh, value);
			nameMap.put(bh, name);
			int num = i + 1;
			noMap.put(bh, "B$" + num);
		}
		System.out.println("pMap:"+pMap.toString());
		// 获取模块编码信息
		Map<String, JSONObject> idMap = new HashMap<>();
		String bms = "";
		for (Object string : mList) {
			JSONObject json = (JSONObject) string;
			String bm = json.getString("BM");
			if (bms.isEmpty()) {
				bms = "'" + bm + "'";
			} else {
				bms += ",'" + bm + "'";
			}
			String id = json.getString("ID");
			idMap.put(id, json);
		}
		String sql = "select  * from  BO_EU_CPQ_INSTALLATION_FEE where   BM in (" + bms + ")";
		List<RowMap> maps = DBSql.getMaps(sql);
		Map<String, RowMap> moduleMap = new HashMap<>();
		if (maps.size() > 0) {
			for (RowMap rowMap : maps) {
				String mkbm = rowMap.getString("BM");
				moduleMap.put(mkbm, rowMap);
			}
		}
		// 对运输工艺数量进行计算
	    List<BO> bos = SDK.getBOAPI().query("BO_EU_CQP_INSTALLATION_FEE_TEMPLATE_GRID").bindId(bindId).list();
	  //存放已经保存的数据
	  	Map<String, BO> boMap = new HashMap<>();
	  	for (BO bo : bos) {
	  		boMap.put(bo.getString("ID"), bo);
	  	}
	    double totalPrice=0;
	    for (String  id : idMap.keySet()) {
			Workbook workbook = new XSSFWorkbook();
			double price=0;
			try {					
				// 获取对应编码的数据信息；
				if (idMap.containsKey(id)) {
					JSONObject json = idMap.get(id);
					String bm = json.getString("BM");
					// 获取模块维护台账的模块数据
					RowMap rowMap = moduleMap.get(bm);
					String rule = rowMap.getString("JSGS"); // 计算规则
					/**
					 * 计算工艺数量。
					 */
					if (!rule.equals("0") && !rule.isEmpty()) {
						Document document = Jsoup.parse(rule);
						  String newRule=document.text();
						Map<String, BO> materMap = new HashMap<>();
						System.out.println("模块计算规则新："+newRule);
						// 创建公式评估器
						FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();
						// 设置单元格值
						Sheet sheet = workbook.createSheet("Sheet1");
						for (int i = 0; i < list.size(); i++) {
							int num = i + 1;
							Cell cellB1 = sheet.createRow(i).createCell(1);
							JSONObject jsonObject = (JSONObject) list.get(i);
							String bh = (String) jsonObject.get("PARMENTIER_NO");
							cellB1.setCellValue(pMap.get(bh));
							System.out.println("cellB1:"+cellB1.getStringCellValue());
						}
						// 获取安装费工艺维护数据中数量计算公式中参数代号，如果有则将代号存放在list中
						for (String key : pMap.keySet()) {
							int num = newRule.indexOf(key);
							if (num > -1) {
								newRule = newRule.replace(key, noMap.get(key));
							}
						}
						// 计算出工艺数量和当前工艺的成本价格
						Cell cellB1 = sheet.createRow(list.size()+1).createCell(3);
						cellB1.setCellFormula(newRule);
						System.out.println("cellB1value:"+cellB1.getCellFormula());
						formulaEvaluator.evaluateFormulaCell(cellB1);
						// 获取公式计算结果
						CellValue cellValue = formulaEvaluator.evaluate(cellB1);
						System.out.println("The result of the formula is: " + cellValue.getNumberValue());
						double number = cellValue.getNumberValue();
						// 总成本价
						double MKDJ = Double.parseDouble(rowMap.getString("DJ"));// 安装费工艺单价
						double MKTotalPrice = number * MKDJ;
						price=MKTotalPrice;
						// 将计算好的数据放入选择的子表数据中，并更新当前数据。
						if(boMap.containsKey(id)) {
							BO mbo=	boMap.get(id);
							mbo.set("DJ", MKDJ);// 单价
							mbo.set("SL", number);// 数量
							mbo.set("XTMC", rowMap.getString("SSXT"));// 系统名称
							mbo.set("LX", rowMap.getString("LX"));// 分类
							mbo.set("ZJ", MKTotalPrice);// 总价
							mbo.set("NAME", rowMap.getString("NAME"));// 名称
							mbo.set("DW", rowMap.getString("DW"));// 单位
							mbo.set("BZ", json.getString("BZ"));// 备注
							mbo.set("BM", rowMap.getString("BM"));// 编码
							mbo.set("XTBM", json.getString("XTBM"));// 系统编码
							SDK.getBOAPI().update("BO_EU_CQP_INSTALLATION_FEE_TEMPLATE_GRID", mbo);

						}else {
							BO mbo=	new BO();
							mbo.set("DJ", MKDJ);// 单价
							mbo.set("SL", number);// 数量
							mbo.set("XTMC", rowMap.getString("SSXT"));// 系统名称
							mbo.set("LX", rowMap.getString("LX"));// 分类
							mbo.set("ZJ", MKTotalPrice);// 总价
							mbo.set("NAME", rowMap.getString("NAME"));// 名称
							mbo.set("DW", rowMap.getString("DW"));// 单位
							mbo.set("BZ", json.getString("BZ"));// 备注
							mbo.set("BM", rowMap.getString("BM"));// 编码
							mbo.set("XTBM", json.getString("XTBM"));// 系统编码
							SDK.getBOAPI().create("BO_EU_CQP_INSTALLATION_FEE_TEMPLATE_GRID", mbo, bindId, userContext.getUID());

						}
						
						}else {
							if(boMap.containsKey(id)) {
								BO mbo=	boMap.get(id);
								mbo.set("DJ", json.getString("DJ"));// 单价
								mbo.set("SL", json.getString("SL"));// 数量
								mbo.set("XTMC", json.getString("SSXT"));// 系统名称
								mbo.set("LX", json.getString("LX"));// 分类
								mbo.set("ZJ", json.getString("ZJ"));// 总价
								double MKDJ = Double.parseDouble(rowMap.getString("ZJ"));// 安装费工艺单价
								price=MKDJ;
								mbo.set("NAME", json.getString("NAME"));// 名称
								mbo.set("DW", json.getString("DW"));// 单位
								mbo.set("BZ", json.getString("BZ"));// 备注
								mbo.set("BM", json.getString("BM"));// 编码
								mbo.set("XTBM", json.getString("XTBM"));// 系统编码
								SDK.getBOAPI().update("BO_EU_CQP_INSTALLATION_FEE_TEMPLATE_GRID", mbo);		
							}else {
								BO mbo=	new BO();
								mbo.set("DJ", json.getString("DJ"));// 单价
								mbo.set("SL", json.getString("SL"));// 数量
								mbo.set("XTMC", json.getString("SSXT"));// 系统名称
								mbo.set("LX", json.getString("LX"));// 分类
								mbo.set("ZJ", json.getString("ZJ"));// 总价
								double MKDJ = Double.parseDouble(rowMap.getString("ZJ"));// 安装费工艺单价
								price=MKDJ;
								mbo.set("NAME", json.getString("NAME"));// 名称
								mbo.set("DW", json.getString("DW"));// 单位
								mbo.set("BZ", json.getString("BZ"));// 备注
								mbo.set("BM", json.getString("BM"));// 编码
								mbo.set("XTBM", json.getString("XTBM"));// 系统编码
								SDK.getBOAPI().create("BO_EU_CQP_INSTALLATION_FEE_TEMPLATE_GRID", mbo, bindId, userContext.getUID());
							}
										
					}
				}
				
			}catch (Exception e){
				 System.out.println("计算安装费发生异常 " + e.getMessage());
			}finally {
	  			 try {
					workbook.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} 
			
			totalPrice=totalPrice+price;
			
			
	    }
	    //将计算出来的总价格存放到费用明细表中的工程安装费中。
	    BO data=SDK.getBOAPI().query("BO_EU_CQP_INSTALLATION_FEE_TEMPLATE_PRICE").addQuery("XH=", "1").detail();
		if(null!=data) {
			data.set("FY", totalPrice);
			SDK.getBOAPI().update("BO_EU_CQP_INSTALLATION_FEE_TEMPLATE_PRICE", data);
		}
		ResponseObject ro = ResponseObject.newOkResponse();
		return ro.toString();
	}

}
